﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Collections;
using Telerik.Windows.Controls;

namespace Infrastructure.AttachedProperties
{
    public static class SelectedItemsForRadListBox
    {
        /// <summary>
        /// SelectedItems Attached Dependency Property.
        /// </summary>
        public static readonly DependencyProperty SelectedItemsProperty =
            DependencyProperty.RegisterAttached("MySelectedItems", typeof(IList), typeof(SelectedItemsForRadListBox),
            new FrameworkPropertyMetadata((IList)null, new PropertyChangedCallback(OnSelectedItemsChanged)));

        /// <summary>
        /// Gets my selected items.
        /// </summary>
        /// <param name="d">The d.</param>
        /// <returns></returns>
        public static IList GetMySelectedItems(DependencyObject d)
        {
            return (IList)d.GetValue(SelectedItemsProperty);
        }

        /// <summary>
        /// Sets my selected items.
        /// </summary>
        /// <param name="d">The d.</param>
        /// <param name="value">The value.</param>
        public static void SetMySelectedItems(DependencyObject d, IList value)
        {
            d.SetValue(SelectedItemsProperty, value);
        }

        /// <summary>
        /// Called when [selected items changed].
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Windows.DependencyPropertyChangedEventArgs"/> instance containing the event data.</param>
        private static void OnSelectedItemsChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            var listBox = sender as RadListBox;
            if (listBox != null)
            {
                ReSetSelectedItems(listBox);
                listBox.SelectionChanged += delegate
                {
                    ReSetSelectedItems(listBox);
                };
            }
        }

        /// <summary>
        /// Res the set selected items.
        /// </summary>
        /// <param name="listBox">The list box.</param>
        private static void ReSetSelectedItems(RadListBox listBox)
        {
            IList selectedItems = GetMySelectedItems(listBox);
            if (selectedItems != null)
            {
                selectedItems.Clear();
                if (listBox.SelectedItems != null)
                {
                    foreach (var item in listBox.SelectedItems)
                    {
                        selectedItems.Add(item);
                    }
                }
            }
        }
    }
}
